<!-- 图片预览 -->
<template>
  <Teleport to="body" :disabled="!teleported">
    <Transition :name="transitionName" :appear="true">
      <div
        v-if="modelValue"
        :class="['ele-image-viewer', customClass]"
        :style="customStyle"
      >
        <ElImageViewer
          v-bind="viewerProps"
          ref="imageViewerRef"
          @close="handleClose"
          @switch="handleSwitch"
          @rotate="handleRotate"
        >
          <template v-for="name in Object.keys($slots)" #[name]="slotProps">
            <slot :name="name" v-bind="slotProps || {}"></slot>
          </template>
        </ElImageViewer>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup>
  import { ref, computed, onDeactivated } from 'vue';
  import { ElImageViewer } from 'element-plus';
  import { omit } from '../utils/common';
  import { imageViewerProps, imageViewerEmits } from './props';

  defineOptions({ name: 'EleImageViewer' });

  const props = defineProps(imageViewerProps);

  const emit = defineEmits(imageViewerEmits);

  /** 组件实例 */
  const imageViewerRef = ref(null);

  /** 组件属性 */
  const viewerProps = computed(() => {
    const options = omit(props, [
      'modelValue',
      'customClass',
      'customStyle',
      'transitionName',
      'keepAlive'
    ]);
    options.teleported = false;
    return options;
  });

  /** 关闭 */
  const handleClose = () => {
    emit('update:modelValue', false);
    emit('close');
  };

  /** 切换图像 */
  const handleSwitch = (index) => {
    emit('switch', index);
  };

  /** 旋转图像 */
  const handleRotate = (deg) => {
    emit('rotate', deg);
  };

  /** 切换图片 */
  const setActiveItem = (index) => {
    imageViewerRef.value && imageViewerRef.value.setActiveItem(index);
  };

  /** 页面失活关闭 */
  onDeactivated(() => {
    handleClose();
  });

  defineExpose({
    imageViewerRef,
    setActiveItem
  });
</script>
